import {createRequestInterceptor, i18n} from "plain-design";
import {env} from "../env";
import {delay} from "@peryl/react-compose";

const requestInterceptor = createRequestInterceptor({ baseURL: env.baseURL });

/*mock 登录过期检测请求*/
requestInterceptor.intercept(/loginExpire/, ({ data }) => {
  return {
    code: 200,
    fail: false,
  };
});

/*mock登录请求*/
requestInterceptor.intercept(/login/, async ({ data }) => {

  console.log('mock -> login', data);

  await delay(1000);

  const body = data as { username: string | undefined, password: string | undefined };

  const username = (body.username)?.toLowerCase();
  if (!username || (username !== 'admin' && username !== 'user')) {
    return {
      code: 500,
      fail: true,
      message: i18n.$intl('page.login.validate.username').d('用户名输入不正确！')
    };
  }
  const password = (body.password)?.toLowerCase();
  if (!password || password !== 'micro.pro') {
    return {
      code: 500,
      fail: true,
      message: i18n.$intl('page.login.validate.password').d('密码输入不正确！')
    };
  }

  return {
    code: 200,
    fail: false,
    result: {
      username,
      position: 'Front Engineer',
      token: username,
      /*60分钟之后过期*/
      expire: Date.now() + (1000 * 60 * 60)
      /*10s后过期*/
      // expire: Date.now() + (1000 * 10)
    }
  };
});

/*根据token获取用户信息*/
requestInterceptor.intercept('/getTokenInfo', async ({ data }) => {
  if (!data || (data.token !== 'admin' && data.token !== 'user')) {
    return {
      code: 500,
      fail: true,
      message: i18n.$intl('page.login.tokenInvalid').d('用户Token信息不正确！')
    };
  }
  return {
    code: 200,
    fail: false,
    result: {
      username: data.username,
      position: 'Front Engineer',
      token: data.token,
      /*10分钟之后过期*/
      expire: Date.now() + (1000 * 60 * 10)
    }
  };
});

/*mock 测试拦截get请求*/
requestInterceptor.intercept('/testGet', ({ param }) => {
  console.log('mock get -> ', param);
  return {
    fail: false,
    message: 'Mock Get Success! ' + JSON.stringify(param)
  };
});

/*mock测试拦截 post json请求*/
requestInterceptor.intercept('/testPostJson', ({ data }) => {
  console.log('mock post json -> ', data);
  return {
    fail: false,
    message: 'Mock Post Json Success!' + JSON.stringify(data)
  };
});

/*mock测试拦截 post form请求*/
requestInterceptor.intercept('/testPostForm', ({ data }) => {
  console.log('mock post form -> ', data);
  return {
    fail: false,
    message: 'Mock Post Form Success!' + JSON.stringify(data)
  };
});
